#include "buf.h"

//create buf object
int buf_init( buf **b )
{
	buf *t = malloc( sizeof(buf) );
	memset( t, 0, sizeof(buf) );
	*b = t;
	return 0;
}


//add some more data to buf of bin/txt
int buf_add( buf *a, buf b ) //like a = a + b
{
	int ret=-1;
	if (a == NULL)
		return -1;
	
	if ((a->size < 0) || (b.size < 1))
	{
		ERROR("Cannot add new data to buffer\n");
		return -1;
	}

	int32_t new_size = a->size + b.size;
	int32_t cpy_size = 0;
	if ( new_size > MAX_BUF_SIZE )
	{
		new_size = MAX_BUF_SIZE;
	}

	cpy_size = new_size - a->size;
	a->data = realloc( a->data, new_size );
	memcpy( a->data+a->size, b.data, cpy_size );
	a->size = new_size;
	ret = cpy_size;

	return ret;
}


//get some data in txt unitl newline
int buf_get_nl( )
{
	
	return 0;
}


//get some data in bin of some size
int buf_get_data( buf *a, int32_t size, buf **b )// a = a - b, b = b;
{
	int ret=-1;
	if ( a == NULL )
	{
		return -1;
	}
	if ( (a->size < 0) || (size < 0))
	{
		ERROR("Cannot get data from buffer\n");
		return -1;
	}

	int new_size = a->size - size;
	int cpy_size = 0;
	if ( new_size < 0 )
	{
		new_size = 0;
		cpy_size = size - a->size;
	}
	
	buf *t = malloc( sizeof(buf) );
	t->data = malloc( cpy_size );
	memcpy( t->data, a->data, cpy_size);
	*b = t;

	//is there something more efective? please i love asm
	int32_t i;
	for (i=0; i<cpy_size; i++)
	{
		a->data[i] = a->data[ i+cpy_size ]; 
	}
	a->data = realloc( a->data, new_size );
	a->size = new_size;

	ret = cpy_size;
	return ret;
}


//clean buf, return memory back
int buf_destroy( buf *b )
{
	if (b == NULL)
	{
		return -1;
	}
	if ( b->data != NULL )
	{
		free( b->data );
		b->data = NULL;
	}
	free( b );
	memset( b, 0, sizeof(buf));

	return 0;
}



